package com.develop.BusinessGatewayService;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Netty Client端
 *
 * 功能：与OMC通信使用
 **/
public class BusinessGatewayClient {
	private static final Logger LOG = LoggerFactory.getLogger(BusinessGatewayClient.class);
	private String host;
	private int port;
	private String cityCode;
	private String firmCode;
	private String omcType;

	public BusinessGatewayClient(String host, int port, String cityCode, String firmCode, String omcType) {
		this.host = host;
		this.port = port;
		this.cityCode = cityCode;
		this.firmCode = firmCode;
		this.omcType = omcType;
	}

	public void start() {
		LOG.info("开始连接业务网关...");
		EventLoopGroup group = new NioEventLoopGroup(4);
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).option(ChannelOption.SO_KEEPALIVE, true).channel(NioSocketChannel.class).handler(new ClientChannelInitializer(host, port, cityCode, firmCode, omcType));
			ChannelFuture f = b.connect(host, port);
			// 断线重连
			f.addListener((ChannelFutureListener) channelFuture -> {
				if (!channelFuture.isSuccess()) {
					final EventLoop loop = channelFuture.channel().eventLoop();
					loop.schedule(() -> {
						LOG.error("业务网关连接不上，开始重连操作...");
						start();
					}, 10L, TimeUnit.SECONDS);
				} else {
					LOG.info("服务端连接成功");
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
